<?php
class Mail {

	protected $receivers	= array();
	protected $subject		= null;
	protected $sender		= null;
	protected $boundary		= null;
	protected $parts		= array();

	public function setSubject($subject) {
		$this->subject = $subject;
	}

	public function getSubject() {
		return $this->subject;
	}

	public function __construct() {
		$config = new Config();
		if (is_string($config->sender)) {
			$this->sender = $config->sender;
		}
		$this->boundary = md5(uniqid(time()));
	}

	public function send() {

		$msg	= "From: %s\r\n"
				. "X-Mailer: PHP 5.x (Ingeen PHP)\r\n"
				. "MIME-Version: 1.0\r\n"
				. "Content-Type: multipart/mixed; boundary=%s%s%s\r\n\r\n"
				. "This is a multi-part message in MIME format.\r\n\r\n";
		$msg	= sprintf($msg, $this->sender, '"', $this->boundary, '"');

		foreach ($this->parts as $part) {
			$msg = sprintf("%s%s", $msg, $part);
		}

		$msg = sprintf("%s--%s--", $msg, $this->boundary);

		return mail(implode(", ", $this->receivers), $this->subject, "", $msg);

	}

	public function from($email) {
		$this->setSender($email);
	}

	public function setSender($email) {
		$this->sender = $email;
	}

	public function to($email) {
		$this->addReceiver($email);
	}

	public function addReceiver($email) {
		$this->receivers[] = $email;
	}

	public function setMessage($message) {
		$part	= "--%s\r\n"
				. "Content-Type: text/plain; charset=utf-8\r\n"
				. "Content-Transfer-Encoding: 7bit\r\n\r\n"
				. "%s\r\n\r\n";
		$this->parts[] = sprintf($part, $this->boundary, wordwrap($message, 70));
	}

	public function setHTMLMessage($message) {
		$part	= "--%s\r\n"
				. "Content-Type: text/html; charset=utf-8\r\n"
				. "Content-Transfer-Encoding: 7bit\r\n\r\n"
				. "%s\r\n\r\n";
		$this->parts[] = sprintf($part, $this->boundary, wordwrap($message, 70));
	}

	public function addAttachment($name, $blob) {
		$part	= "--%s\r\n"
				. "Content-Type: application/octet-stream; name=%s%s%s\r\n"
				. "Content-Transfer-Encoding: base64\r\n"
				. "Content-Disposition: attachment; filename=%s%s%s\r\n\r\n"
				. "%s\r\n\r\n";
		$this->parts[] = sprintf($part, $this->boundary,
								'"', $name, '"',
								'"', $name, '"',
								chunk_split(base64_encode($blob)));
	}

}